package io.finer.erp.jeecg.bas.controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.finer.erp.jeecg.stock.vo.SumQtyVo2;
import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Maps;

import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.stock.entity.StkInventory;
import io.finer.erp.jeecg.stock.entity.StkMaterielStorage;
import io.finer.erp.jeecg.stock.vo.SumQtyVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 物料
 * @Author: jeecg-boot
 * @Date:   2020-08-25
 * @Version: V1.0
 */
@Api(tags="物料")
@RestController
@RequestMapping("/bas/basMaterial")
@Slf4j
public class BasMaterialController extends JeecgController<BasMaterial, IBasMaterialService> {
	@Autowired
	private IBasMaterialService basMaterialService;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	
	
	/**
	 * 分页列表查询
	 *
	 * @param basMaterial
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "物料-分页列表查询")
	@ApiOperation(value="物料-分页列表查询", notes="物料-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BasMaterial basMaterial,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BasMaterial> queryWrapper = QueryGenerator.initQueryWrapper(basMaterial, req.getParameterMap());
		Page<BasMaterial> page = new Page<BasMaterial>(pageNo, pageSize);
		IPage<BasMaterial> pageList = basMaterialService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	 @AutoLog(value = "物料库存-查询自有产品下的所有物料信息")
	 @ApiOperation(value="物料库存-查询自有产品下的所有物料信息", notes="物料库存-查询自有产品下的所有物料信息")
	 @GetMapping(value = "/getMaterials")
	 public Result<?> getMaterials(StkMaterielStorage storage,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							   HttpServletRequest request){
		 String od = request.getParameter("order");//排序
		 String com = request.getParameter("column");
		 String column = propertyToField(com);
		 StringBuffer order = new StringBuffer();
		 if(StringUtils.equals(column, "create_time")) {
			 column = "id";
		 }
		 if(StringUtils.equals(column, "id")||StringUtils.equals(column, "width")||StringUtils.equals(column, "length")) {
			 order.append("mate.");
		 }
		 if(StringUtils.equals(column, "qty")||StringUtils.equals(column, "unit_id")) {
			 order.append("inve.");
		 }
		 if(StringUtils.equals(column, "warehouse_id_dict_text")) {
			 order.append("house.");
			 column = "name";
		 }
		 order.append(column);
		 order.append(" ");
		 order.append(od);
		 Result<Page<StkMaterielStorage>> result = new Result<Page<StkMaterielStorage>>();
		 String warehouseId=request.getParameter("warehouseId");//仓库
		 String parameter = request.getParameter("categoryId");//物料分组
		 String materialCode = request.getParameter("materialCode");//物料编号
		 String width_begin = request.getParameter("width_begin");//宽--开始
		 String width_end = request.getParameter("width_end");//宽--结束
		 String length_begin = request.getParameter("length_begin");//长--开始
		 String length_end = request.getParameter("length_end");//长--结束

		 Page<StkMaterielStorage> pageList = new Page<StkMaterielStorage>(pageNo,pageSize);
		 //长 宽  物料编号  仓库   物料分类
		 Page<StkMaterielStorage> list=basMaterialService.getMaterials(pageList,warehouseId,
				 parameter,materialCode,width_begin,width_end,length_begin,length_end,order.toString());

		 result.setSuccess(true);
		 result.setResult(list);
		 return result;
	 }
	 
	 @AutoLog(value = "物料库存-统计数量")
	 @ApiOperation(value="物料库存-统计数量", notes="物料库存-统计数量")
	 @GetMapping(value = "/getMaterialsCount")
	 public Result<?> getMaterialsCount(StkMaterielStorage storage,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							   HttpServletRequest request){
		 String od = request.getParameter("order");//排序
		 String com = request.getParameter("column");
		 String column = propertyToField(com);
		 StringBuffer order = new StringBuffer();
		 if(StringUtils.equals(column, "create_time")||StringUtils.equals(column, "width")||StringUtils.equals(column, "length")) {
			 order.append("mate.");
		 }
		 if(StringUtils.equals(column, "qty")||StringUtils.equals(column, "unit_id")) {
			 order.append("inve.");
		 }
		 order.append(column);
		 order.append(" ");
		 order.append(od);
		 System.err.println(order.toString());
		 Result<BigDecimal> result = new Result<BigDecimal>();
		 String warehouseId=request.getParameter("warehouseId");//仓库
		 String parameter = request.getParameter("categoryId");//物料分组
		 String materialCode = request.getParameter("materialCode");//物料编号
		 String width_begin = request.getParameter("width_begin");//宽--开始
		 String width_end = request.getParameter("width_end");//宽--结束
		 String length_begin = request.getParameter("length_begin");//长--开始
		 String length_end = request.getParameter("length_end");//长--结束

		 Page<StkMaterielStorage> pageList = new Page<StkMaterielStorage>(pageNo,pageSize);
		 //长 宽  物料编号  仓库   物料分类
		 List<StkMaterielStorage> list=basMaterialService.getMaterialsCount(warehouseId,
				 parameter,materialCode,width_begin,width_end,length_begin,length_end,order.toString());
		 BigDecimal basMaterialCount = BigDecimal.ZERO;
		 if(list!=null&&list.size()>0) {
			 for(StkMaterielStorage stkMaterielStorage:list) {
				 basMaterialCount = basMaterialCount.add(stkMaterielStorage.getQty());
			 }
			 result.setSuccess(true);
			 result.setResult(basMaterialCount.stripTrailingZeros());
		 }else {
			 result.setSuccess(true);
			 result.setResult(basMaterialCount.stripTrailingZeros());
		 }
		 
		 return result;
	 }

	 /**
		 * 对象属性转换为字段  例如：userName to user_name
		 * @param property 字段名
		 * @return
		 */
		private String propertyToField(String property) {
			if (null == property) {
				return "";
			}
			char[] chars = property.toCharArray();
			StringBuffer sb = new StringBuffer();
			for (char c : chars) {
				if (CharUtils.isAsciiAlphaUpper(c)) {
					sb.append("_" + StringUtils.lowerCase(CharUtils.toString(c)));
				} else {
					sb.append(c);
				}
			}
			return sb.toString();
		}



	@AutoLog(value = "物料-查询自有产品下的所有物料信息")
	@ApiOperation(value="物料-查询自有产品下的所有物料信息", notes="物料-查询自有产品下的所有物料信息")
	@GetMapping(value = "/queryAllBasMaterialByCatagroyId")
	public Result<?> queryAllBasMaterialByCatagroyId() {
		//查询自有产品下的所有物料
		String catagroyId="1296737703785730050";
		List<BasMaterial> bsList=basMaterialService.selectDistinctMaterialByCategoryId(catagroyId);
		List<DictModel> list=new ArrayList<DictModel>();
		if(null!=bsList&&bsList.size()>0) {
			for(BasMaterial bm:bsList) {
				DictModel dict=new DictModel();
				dict.setValue(bm.getId());//物料主键id
				dict.setText(bm.getName());
				list.add(dict);
			}
		}
		return Result.ok(list);
	}
	
	/**
	 *   添加
	 *
	 * @param basMaterial
	 * @return
	 */
	@AutoLog(value = "物料-添加")
	@ApiOperation(value="物料-添加", notes="物料-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BasMaterial basMaterial) {
		String categoryId = basMaterial.getCategoryId();
		BasMaterial result = this.basMaterialService.getMaterialCode(categoryId);
		if (null == result || StringUtils.isBlank(result.getCodeImg())) {
			return Result.error("系统错误");
		}
		basMaterial.setCode(result.getCode()).setCodeImg(result.getCodeImg());
		basMaterialService.save(basMaterial);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param basMaterial
	 * @return
	 */
	@AutoLog(value = "物料-编辑")
	@ApiOperation(value="物料-编辑", notes="物料-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BasMaterial basMaterial) {
		basMaterialService.updateById(basMaterial);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "物料-通过id删除")
	@ApiOperation(value="物料-通过id删除", notes="物料-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		basMaterialService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "物料-批量删除")
	@ApiOperation(value="物料-批量删除", notes="物料-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.basMaterialService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "物料-通过id查询")
	@ApiOperation(value="物料-通过id查询", notes="物料-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BasMaterial basMaterial = basMaterialService.getById(id);
		if(basMaterial==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(basMaterial);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param basMaterial
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasMaterial basMaterial) {
        return super.exportXls(request, basMaterial, BasMaterial.class, "物料");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BasMaterial.class);
    }

    
    /**
     * @Description 停止预警
     * @param ids
     * @return
     * Create at: 2020-08-26 10:44:27
     * @author: duanyong
     * Revision:
     *    2020-08-26 10:44:27 - first revision by duanyong
     *        
     */
    @GetMapping(value = "/stopWarning")
    public Result<?> stopWarning(@RequestParam(name="ids", required=true) String ids){
    	List<String> idList = Arrays.asList(ids.split(","));
    	Result<Object> result = new Result<>();
    	
    	return this.basMaterialService.stopWarning(idList, result);
    }
    
    /**
     * @Description 批量生成物料
     * @param categoryId 物料分类ID
     * @param number 物料数量
     * @return
     * Create at: 2020-08-31 11:26:01
     * @author: duanyong
     * Revision:
     *    2020-08-31 11:26:01 - first revision by duanyong
     *        
     */
    //TODO
    @AutoLog(value = "物料-批量添加")
	@ApiOperation(value="物料-批量添加", notes="物料-批量添加")
	@GetMapping(value = "/batchAdd")
    public Result<?> batchAdd(@RequestParam(name="batchCategoryId", required=true)String batchCategoryId
    		, @RequestParam(name="batchNum", required=true)Integer batchNum){
    	return this.basMaterialService.batchAdd(batchCategoryId, batchNum);
    }
    
    /**
     * @Description 联动查询物料
     * @param typeId
     * @return
     * Create at: 2020-08-26 17:18:58
     * @author: duanyong
     * Revision:
     *    2020-08-26 17:18:58 - first revision by duanyong
     *        
     */
    @GetMapping(value = "/getMaterialByCategory")
    public Result<?> getMaterialByCategory(@RequestParam(name="typeId", required=true) String typeId){
    	Result<Object> result = new Result<>();
    	if (StringUtils.isBlank(typeId)) {
    		return result.error500("系统繁忙");
    	}
    	LambdaQueryWrapper<BasMaterialCategory> cQuery = new LambdaQueryWrapper<>();
    	cQuery.eq(BasMaterialCategory::getCode, typeId);
    	BasMaterialCategory category = this.categoryService.getOne(cQuery);
    	if (null == category) {
    		return result.error500("系统繁忙");
    	}
    	
    	LambdaQueryWrapper<BasMaterial> query = new LambdaQueryWrapper<>();
    	query.eq(BasMaterial::getIsEnabled, 1);
    	query.eq(BasMaterial::getCategoryId, category.getId());
    	query.orderByAsc(BasMaterial::getName);
    	List<BasMaterial> list = basMaterialService.list(query);
    	result.setResult(list);
    	result.setSuccess(true);
    	result.setCode(200);
    	
    	return result;
    }


    @GetMapping(value = "sumQty")
	 public Result<?> sumQty(StkMaterielStorage storage,
							 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							 HttpServletRequest request){
		Page<StkMaterielStorage> page = new Page<StkMaterielStorage>(pageNo,pageSize);
		Result<Object> result = new Result<>();
		Page<StkMaterielStorage>  list=basMaterialService.countMateriels(page, storage);
		result.setResult(list);
		result.setSuccess(true);
		result.setCode(200);

		return result;
	}

    
    @GetMapping(value = "getSumQtyDetail")
	 public Result<?> getSumQtyDetail(StkMaterielStorage storage,
							 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
							 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
							 HttpServletRequest request){
		Page<StkInventory> page = new Page<StkInventory>(pageNo,pageSize);
		IPage<StkInventory>  list=basMaterialService.getSumQtyDetail(page, storage);
		return Result.ok(list);
	}


    /**
     * @Description 维护物料的配方
     * @param materialId 多个物料ID 用","隔开
     * @param fomulaId
     * @return
     * Create at: 2021-02-04 14:12:22
     * @author: duany
     * Revision:
     *    2021-02-04 14:12:22 - first revision by duany
     *
     */
    @GetMapping("/setMaterialFomula")
    public Result<?> setMaterialFomula(@RequestParam("materialId")String materialId, @RequestParam("fomulaId")String fomulaId){
    	return this.basMaterialService.setMaterialFomula(materialId, fomulaId);
    }




	 /**
	  * 导出物料统计excel
	  *
	  * @param request
	  * @param basMaterial
	  */
	 @RequestMapping(value = "/sumMaterialXls")
	 public ModelAndView exportXlsByPid(HttpServletRequest request, BasMaterial basMaterial) {


		 String materialName = request.getParameter("materialName");
		 String materialId = request.getParameter("categoryId");
		 String pid=request.getParameter("pid");

		 //Step.2 获取导出数据
		 List<SumQtyVo> stkTrayDetailList = basMaterialService.countMaterielsXls(materialId,pid,materialName);


		 // Step.4 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "物料统计表");
		 mv.addObject(NormalExcelConstants.CLASS, SumQtyVo.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("物料统计表数据",  "物料统计表"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, stkTrayDetailList);
		 return mv;
	 }

	 /**
	  * 导出物料统计excel
	  *
	  * @param request
	  * @param basMaterial
	  */
	 @RequestMapping(value = "/sumMaterialXls2")
	 public ModelAndView exportXlsByPid2(HttpServletRequest request, BasMaterial basMaterial) {


		 String materialName = request.getParameter("materialName");
		 String materialId = request.getParameter("categoryId");
		 String pid=request.getParameter("pid");

		 //Step.2 获取导出数据
		 List<SumQtyVo2> stkTrayDetailList = basMaterialService.countMaterielsXls2(materialId,pid,materialName);


		 // Step.4 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "库存统计表");
		 mv.addObject(NormalExcelConstants.CLASS, SumQtyVo2.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("库存统计表数据",  "库存统计表"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, stkTrayDetailList);
		 return mv;
	 }
	 
	@RequestMapping(value = "getQrCode", method = RequestMethod.GET)
	public Result<?> getQrCode(@RequestParam(name="id")String id){
		BasMaterial material = this.basMaterialService.getById(id);
		if(null == material) {
			return Result.error("未找到物料");
		}
		String code = material.getCode();
		String fileName = code + ".png";
		String barPath = "bar/" + fileName;
		String filePath = uploadpath + File.separator + barPath;
		cn.hutool.extra.qrcode.QrCodeUtil.generate(code, 300, 300, new File(filePath));
		Result<Object> result = new Result<>();
		result.setSuccess(Boolean.TRUE);
		result.setCode(CommonConstant.SC_OK_200);
		Map<String, String> map = Maps.newHashMap();
		map.put("url", barPath);
		result.setResult(map);
		return result;
	}
 }
